// MedicalRulesEngine.API/Program.cs
using MedicalRulesEngine.API.Extensions;
using MedicalRulesEngine.API.Middleware;
using MedicalRulesEngine.Core.Extensions;
using Serilog;
using System.Text.Json;
using System.Text.Json.Serialization;

var builder = WebApplication.CreateBuilder(args);

// 配置Serilog日志
Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(builder.Configuration)
    .Enrich.FromLogContext()
    .WriteTo.Console()
    .WriteTo.File("logs/medical-rules-engine-.txt", rollingInterval: RollingInterval.Day)
    .CreateLogger();

builder.Host.UseSerilog();

// 添加服务到容器
builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
        options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
        options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
        options.JsonSerializerOptions.WriteIndented = true;
    });

// 添加API探索服务
builder.Services.AddEndpointsApiExplorer();

// 添加Swagger文档
builder.Services.AddSwaggerDocumentation();

// 添加CORS策略
builder.Services.AddCorsPolicy(builder.Configuration);

// 添加健康检查
builder.Services.AddHealthChecks(builder.Configuration);

// 添加医疗规则引擎服务
builder.Services.AddMedicalRulesEngine(builder.Configuration);

// 添加响应缓存
builder.Services.AddResponseCaching();

// 添加内存缓存
builder.Services.AddMemoryCache();

// 添加HTTP客户端
builder.Services.AddHttpClient();

var app = builder.Build();

// 配置HTTP请求管道
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
    app.UseSwaggerDocumentation(app.Environment.IsDevelopment());
    app.UseCors("DevelopmentCorsPolicy");
}
else
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
    app.UseCors("DefaultCorsPolicy");
}

// 添加全局异常处理中间件
app.UseMiddleware<ExceptionHandlingMiddleware>();

// 添加默认页重定向到Swagger
app.Use(async (context, next) =>
{
    if (context.Request.Path == "/")
    {
        context.Response.Redirect("/api-docs");
        return;
    }
    await next();
});

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.UseResponseCaching();

// 配置端点
app.MapControllers();

// 配置健康检查端点
app.MapHealthChecks("/health", new Microsoft.AspNetCore.Diagnostics.HealthChecks.HealthCheckOptions
{
    ResponseWriter = async (context, report) =>
    {
        context.Response.ContentType = "application/json";
        var response = new
        {
            status = report.Status.ToString(),
            checks = report.Entries.Select(x => new
            {
                name = x.Key,
                status = x.Value.Status.ToString(),
                description = x.Value.Description,
                duration = x.Value.Duration.TotalMilliseconds
            }),
            duration = report.TotalDuration.TotalMilliseconds
        };
        await context.Response.WriteAsync(JsonSerializer.Serialize(response, new JsonSerializerOptions
        {
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
            WriteIndented = true
        }));
    }
});

// 初始化数据
try
{
    await app.Services.InitializeMedicalRulesEngineAsync();
    Log.Information("医疗规则引擎初始化完成");
}
catch (Exception ex)
{
    Log.Fatal(ex, "医疗规则引擎初始化失败");
    throw;
}

Log.Information("医疗规则引擎 API 启动完成，环境: {Environment}", app.Environment.EnvironmentName);

app.Run();
